﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DreamBuilder.UI.UserControls.DataAccess.Services;
using System.Data;
using DreamBuilder.Core.Container;
using System.IO;
using CommonModule;
using ePlanet.Entities;

namespace Web.Views.DataManage.PLuploads
{
    /// <summary>
    /// ArchiveExportHandler 的摘要说明
    /// </summary>
    public class ArchiveExportHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string userId = context.Request.QueryString["UserId"];
                string catalogId = context.Request.QueryString["CatalogId"];
                string type = context.Request.QueryString["Type"];
                string requestType = context.Request.QueryString["RequestType"];
                string dataId = context.Request.QueryString["DataId"];
                string dbHelperName = context.Request.QueryString.Get("DbHelper");
                if (dbHelperName == string.Empty)
                {
                    switch (catalogId)
                    {
                        case "1"://文书件
                        case "101"://文书卷
                        case "102"://文书卷内件
                            dbHelperName = "DocumentFile";
                            break;
                        case "2": //光盘类 E
                            dbHelperName = "CDKind";
                            break;
                        case "3": //科学技术研究类 F
                            dbHelperName = "Technology";
                            break;
                        case "4": //建设项目类 G
                            dbHelperName = "BuildProjectFile";
                            break;
                        case "5": //设备仪器类 H
                            dbHelperName = "Equipment";
                            break;
                        case "61": //会计凭证 I01
                        case "62": //会计账簿 I02
                        case "63": //财务报告 I03
                        case "64": //其他 I04
                            dbHelperName = "AccountFile";
                            break;
                        case "71": //勘探综合
                        case "7101"://勘探综合卷
                        case "7102"://勘探综合卷内件
                        case "72": //勘探单井
                            dbHelperName = "oilsearch";
                            break;
                        case "81": //声像
                        case "82": //声像
                        case "83": //声像
                            dbHelperName = "audiofile";
                            break;
                        case "91": //荣誉 R01
                            dbHelperName = "RealKind";
                            break;
                        default:
                            throw new Exception("no such catalogId");
                    }
                }
                if (requestType == "GetFileList")
                {
                    DataHelper dataHelper = new DataHelper();
                    List<AttachmentInfo> AttachmentInfos = new List<AttachmentInfo>();
                    string requestData = context.Request.Form["data"].ToString();
                    List<string> dataIds = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(requestData);
                    DataTable table =  dataHelper.GetAttachmentIds(dataIds, dbHelperName);
                    foreach (DataRow row in table.Rows)
                    {
                        AttachmentInfos.Add(new AttachmentInfo { Id = string.Concat(row["ATTACHMENTID"]), Name = string.Concat(row["ATTACHMENTNAME"]), FileSize = int.Parse(string.Concat(row["ATTACHMENTSIZE"])) });
                    }
                    string responStr = Newtonsoft.Json.JsonConvert.SerializeObject(AttachmentInfos);
                    context.Response.ContentType = "text/plain";
                    context.Response.Write(responStr);
                }
                else if (requestType == "TemplateFile")
                {
                    if (File.Exists(Uri.UnescapeDataString(dataId)))
                    {
                        using (FileStream fs = new FileStream(Uri.UnescapeDataString(dataId), FileMode.Open))
                        {
                            byte[] templateDatas = new byte[fs.Length];
                            fs.Read(templateDatas, 0, templateDatas.Length);
                            //context.Response.Headers.Add("DataBaseFileName", Path.GetFileName(fs.Name));
                            //context.Response.Headers.Add("DataBaseFileSize", string.Concat(templateDatas.Length / 1024));
                            context.Response.ContentType = "application/octet-stream";
                            context.Response.OutputStream.Write(templateDatas, 0, templateDatas.Length);
                        }
                    }
                    else
                    {
                        throw new Exception("未能正确生成导出数据文件");
                    }
                }
                else
                {
                    AttachmentDAL AttachmentDAL = UContainer.Resolve<AttachmentDAL>();
                    AttachmentDAL.AttachmentDBHelperString = dbHelperName;
                    DataTable oDataTable = AttachmentDAL.GetAttachmentByID(dataId);
                    if (oDataTable != null && oDataTable.Rows.Count > 0)
                    {
                        byte[] attachmentContent = (byte[])oDataTable.Rows[0]["AttachmentContent"];
                        string fileName = string.Concat(oDataTable.Rows[0]["ATTACHMENTNAME"]);
                        int fileSize = int.Parse(string.Concat(oDataTable.Rows[0]["ATTACHMENTSIZE"]));
                        //context.Response.Headers.Add("DataBaseFileName", fileName);
                        //context.Response.Headers.Add("DataBaseFileSize", string.Concat(fileSize));
                        context.Response.ContentType = "application/octet-stream";
                        context.Response.OutputStream.Write(attachmentContent,0,attachmentContent.Length);
                    }
                    else
                    {
                        throw new Exception("数据库中未找到文件");
                    }
                }
            }
            catch (Exception ex)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("Error: " + ex.Message);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}